<template>
  <base-modal :width="modAlProps.width" :isVisible="props.isVisible" :title="props.isPigeonhole ? '出档' : modAlProps.title"
    :buttons="buttons" @handleOk="buttonMessage" @handleCancle="handleCancle" class="site_modal">
    <template v-slot:body>
      <div>
        <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
          ref="columnFrom">
          <!-- </a-form-item> -->
          <a-form-item :label="'选择栏目'">
            <a-input v-model:value="searchValue" placeholder="搜索栏目名称">
              <template #suffix>
                <i class="iconfont icon-search"></i>
              </template>
            </a-input>
          </a-form-item>

          <a-form-item :label="''" v-if="gData && gData.length > 0">
            <div class="openorclose" @click="openorclose" v-show="isOpen">
              <a>全部收起</a>
              <i class="iconfont icon-up" style="font-size: 24px"> </i>
            </div>
            <div class="openorclose" @click="openorclose" v-show="!isOpen">
              <a>全部展开</a>
              <i class="iconfont icon-down" style="font-size: 24px"> </i>
            </div>
            <a-tree :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="gData"
              @expand="onExpand" :fieldNames="fieldNames" class="atree" @select="selectColumn"
              :selectedKeys="selectedKeys" v-if="gData.length" :height="300">
              <template #title="record">
                <!-- <span>{{ record.id }}</span> -->
                <span v-if="record.channelName.indexOf(searchValue) > -1">
                  {{ record.channelName.substr(0, record.channelName.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{
                    record.channelName.substr(
                      record.channelName.indexOf(searchValue) + searchValue.length
                    )
                  }}
                </span>
                <span v-else>{{ record.channelName }}</span>
              </template>
            </a-tree>

          </a-form-item>
        </a-form>
      </div>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, defineComponent, watch } from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import request from "@/api/index";
import { Modal, message } from "ant-design-vue";
import type { TreeProps } from "ant-design-vue";
import getters from "@/store/getters";
import { array } from "vue-types";
//interface
interface Options {
  [propName: string | number]: any;
}
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  contentIds: {
    type: Array,
    default: [],
  },
  isPigeonhole: {
    type: Boolean,
    default: false
  },
  channelId: {
    type: [String, Number],
    default: false
  }
});
//data
//模态框数据
const modAlProps = reactive<Options>({
  width: "M",
  title: "还原",
});
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "channelName",
  key: "id",
});
const formState = ref<dataSourceType>({});
//模态框button按钮个数和文案修改

let buttons = ref<Options[]>([
  {
    text: "确定",
    "html-type": "submit",
  },
]);
const siteOptions = ref<dataSourceType[]>([]);
const siteId = ref<any[]>([]);
const userInfo = getters.userInfo();
const expandedKeys = ref<(string | number)[]>([]);
const searchValue = ref<string>("");
const autoExpandParent = ref<boolean>(true);
const gData = ref<any[]>([]);
const dataList: TreeProps["treeData"] = [];
const isOpen = ref<boolean>(true); //是否展开或收起.
const channelId = ref<number | string>('');
const onExpand = (keys: string[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};
const selectedKeys = ref<(number | string)[]>([]);;
const parentId_columns = ref<(number | string)[]>([]);
watch(searchValue, (value) => {
  parentKey.value = [];
  if (value) {
    dataList.map((item: any) => {
      getParentKey(value, item);
    });
  }
  expandedKeys.value = parentKey.value;
  searchValue.value = value;
  autoExpandParent.value = true;
});
const parentKey = ref<(string | number)[]>([]);
const getParentKey = (value: string | number, node: any) => {
  if (node.channelName.indexOf(value) > -1) {
    // parentKey = node.id;
    parentKey.value.push(node.id);
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  } else {
    if (node.children) {
      node.children.map((item: any) => {
        getParentKey(value, item);
      });
    }
  }
};
//获取栏目层级树列表
const fetchChannelListBySiteId = async () => {
  let params = {
    allPermFilter: true,
    siteId: userInfo.siteId,
  };
  let data = await request.fetchChannelListBySiteId(params);
  nextTick(() => {

    dataList.push(...data);
    loop(data);
    nextTick(() => {
      gData.value = JSON.parse(JSON.stringify(data)) || [];
      traversal(dataList);
      if (!parentId_columns.value.includes(props.channelId)) {
        selectedKeys.value.push(props.channelId);
      }
    })
  })

};

const selectColumn = async (val: any) => {
  if (!parentId_columns.value.includes(val[0])) {
    selectedKeys.value = val;
  }

};
const openorclose = () => {
  isOpen.value = !isOpen.value;
  if (!isOpen.value) {
    expandedKeys.value = [];
  } else {
    traversal(dataList);
  }
};
const traversal = (data: any) => {
  data.map((item: any) => {
    parentKey.value.push(item.id);
    if (item.children) {
      traversal(item.children);
    }
  });
  expandedKeys.value = parentKey.value;
};
const loop = (data: dataSourceType[]) => {
  data.forEach((item: any) => {
    if (item.children && item.children.length) {
      parentId_columns.value.push(item.id)
      loop(item.children)
    } else {
    }
  })
}
// 还原调取接口 、出档接口
const buttonMessage = (msg: dataSourceType) => {
  let params = {
    contentIds: props.contentIds,
    channelId: selectedKeys.value[0],
  };
  if (!params.channelId) {
    message.error('栏目不能为空')
    return
  }
  request[props.isPigeonhole ? 'fetchContentUnfile' : 'fetchContentRestore']
    (params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        handleOk();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 树节点选中
const selectTreeNode = (val: any) => {
  console.log(val, '11')
}
const emits = defineEmits(["handleOk", "handleCancle"]);
const handleOk = () => {
  emits("handleOk");
};

const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
//onmounted
onMounted(async () => {
  // fetchSiteTreeList();
  fetchChannelListBySiteId()
});
</script>

<style lang="scss" scoped>
::v-deep(.ant-form-item-label) {
  width: 80px;
}

::v-deep(.atree) {
  margin-left: 80px;
}

.icon-search {
  font-size: 14px !important;
  color: rgba(0, 0, 0, 0.45);
}

.openorclose {
  margin-left: 80px !important;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 16px;
  font-size: 14px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #1f6ded;

  .iconfont {
    margin-left: 5px;
  }
}
</style>
